<template>
  <div class="courses-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <Breadcrumb :items="breadcrumbItems" />
        <div class="header-content">
          <h1 class="page-title">课程中心</h1>
          <p class="page-subtitle">发现优质课程，提升专业技能</p>
        </div>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="search-filter-section">
      <div class="container">
        <div class="search-bar">
          <SearchBox
            v-model="searchKeyword"
            placeholder="搜索课程名称、讲师、技能..."
            :show-advanced="true"
            :categories="categories"
            :difficulties="difficulties"
            @search="handleSearch"
            @advanced-search="handleAdvancedSearch"
          />
        </div>
        
        <div class="filter-tabs">
          <el-tabs v-model="activeCategory" @tab-change="handleCategoryChange">
            <el-tab-pane label="全部" name="all" />
            <el-tab-pane
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :name="category.value"
            />
          </el-tabs>
        </div>
        
        <div class="filter-controls">
          <div class="filter-left">
            <el-select
              v-model="filters.difficulty"
              placeholder="难度等级"
              clearable
              @change="handleFilterChange"
            >
              <el-option
                v-for="difficulty in difficulties"
                :key="difficulty.value"
                :label="difficulty.label"
                :value="difficulty.value"
              />
            </el-select>
            
            <el-select
              v-model="filters.priceType"
              placeholder="价格类型"
              clearable
              @change="handleFilterChange"
            >
              <el-option label="全部" value="all" />
              <el-option label="免费" value="free" />
              <el-option label="付费" value="paid" />
            </el-select>
            
            <el-select
              v-model="filters.duration"
              placeholder="课程时长"
              clearable
              @change="handleFilterChange"
            >
              <el-option label="1小时以内" value="short" />
              <el-option label="1-5小时" value="medium" />
              <el-option label="5小时以上" value="long" />
            </el-select>
            
            <el-button
              v-if="hasActiveFilters"
              text
              type="primary"
              @click="clearFilters"
            >
              清除筛选
            </el-button>
          </div>
          
          <div class="filter-right">
            <el-select
              v-model="sortBy"
              placeholder="排序方式"
              @change="handleSortChange"
            >
              <el-option label="综合排序" value="default" />
              <el-option label="最新发布" value="newest" />
              <el-option label="最受欢迎" value="popular" />
              <el-option label="评分最高" value="rating" />
              <el-option label="价格从低到高" value="price_asc" />
              <el-option label="价格从高到低" value="price_desc" />
            </el-select>
            
            <el-button-group class="view-mode">
              <el-button
                :type="viewMode === 'grid' ? 'primary' : 'default'"
                @click="viewMode = 'grid'"
              >
                <el-icon><Grid /></el-icon>
              </el-button>
              <el-button
                :type="viewMode === 'list' ? 'primary' : 'default'"
                @click="viewMode = 'list'"
              >
                <el-icon><List /></el-icon>
              </el-button>
            </el-button-group>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 课程列表 -->
    <div class="courses-content">
      <div class="container">
        <!-- 结果统计 -->
        <div class="results-info" v-if="!loading">
          <span class="results-count">
            共找到 <strong>{{ total }}</strong> 门课程
          </span>
          <div class="active-filters" v-if="activeFilters.length > 0">
            <span class="filter-label">当前筛选：</span>
            <el-tag
              v-for="filter in activeFilters"
              :key="filter.key"
              closable
              @close="removeFilter(filter.key)"
            >
              {{ filter.label }}
            </el-tag>
          </div>
        </div>
        
        <!-- 课程网格/列表 -->
        <div
          class="courses-container"
          :class="{
            'grid-view': viewMode === 'grid',
            'list-view': viewMode === 'list'
          }"
          v-loading="loading"
        >
          <template v-if="courses.length > 0">
            <CourseCard
              v-for="course in courses"
              :key="course.id"
              :course="course"
              :view-mode="viewMode"
              @click="viewCourse(course.id)"
              @favorite="handleFavorite"
              @enroll="handleEnroll"
            />
          </template>
          
          <!-- 空状态 -->
          <div v-else-if="!loading" class="empty-state">
            <el-empty
              description="暂无符合条件的课程"
              :image-size="120"
            >
              <template #image>
                <el-icon :size="120" color="var(--el-color-info)">
                  <Reading />
                </el-icon>
              </template>
              <el-button type="primary" @click="clearFilters">
                清除筛选条件
              </el-button>
            </el-empty>
          </div>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-container" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[12, 24, 36, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
    
    <!-- 推荐课程 -->
    <div class="recommended-section" v-if="recommendedCourses.length > 0">
      <div class="container">
        <div class="section-header">
          <h2 class="section-title">为您推荐</h2>
          <p class="section-subtitle">基于您的学习偏好推荐</p>
        </div>
        
        <div class="recommended-courses">
          <CourseCard
            v-for="course in recommendedCourses"
            :key="course.id"
            :course="course"
            view-mode="grid"
            @click="viewCourse(course.id)"
            @favorite="handleFavorite"
            @enroll="handleEnroll"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Grid, List, Reading } from '@element-plus/icons-vue'
import { useCourseStore } from '@/stores/course'
import { useUserStore } from '@/stores/user'
import SearchBox from '@/components/common/SearchBox.vue'
import Breadcrumb from '@/components/common/Breadcrumb.vue'
import CourseCard from '@/components/course/CourseCard.vue'

const router = useRouter()
const route = useRoute()
const courseStore = useCourseStore()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const activeCategory = ref('all')
const viewMode = ref('grid')
const sortBy = ref('default')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const courses = ref([])
const recommendedCourses = ref([])

// 筛选条件
const filters = reactive({
  difficulty: '',
  priceType: 'all',
  duration: '',
  rating: '',
  instructor: ''
})

// 面包屑导航
const breadcrumbItems = ref([
  { title: '首页', path: '/' },
  { title: '课程中心', path: '/courses' }
])

// 分类选项
const categories = ref([
  { label: '前端开发', value: 'frontend' },
  { label: '后端开发', value: 'backend' },
  { label: '移动开发', value: 'mobile' },
  { label: '数据科学', value: 'data-science' },
  { label: '人工智能', value: 'ai' },
  { label: '云计算', value: 'cloud' },
  { label: '网络安全', value: 'security' },
  { label: '产品设计', value: 'design' },
  { label: '项目管理', value: 'management' }
])

// 难度选项
const difficulties = ref([
  { label: '入门', value: 'beginner' },
  { label: '初级', value: 'elementary' },
  { label: '中级', value: 'intermediate' },
  { label: '高级', value: 'advanced' },
  { label: '专家', value: 'expert' }
])

// 计算属性
const hasActiveFilters = computed(() => {
  return Object.values(filters).some(value => value && value !== 'all') ||
         activeCategory.value !== 'all' ||
         searchKeyword.value.trim()
})

const activeFilters = computed(() => {
  const result = []
  
  if (searchKeyword.value.trim()) {
    result.push({
      key: 'keyword',
      label: `关键词: ${searchKeyword.value}`
    })
  }
  
  if (activeCategory.value !== 'all') {
    const category = categories.value.find(c => c.value === activeCategory.value)
    if (category) {
      result.push({
        key: 'category',
        label: `分类: ${category.label}`
      })
    }
  }
  
  if (filters.difficulty) {
    const difficulty = difficulties.value.find(d => d.value === filters.difficulty)
    if (difficulty) {
      result.push({
        key: 'difficulty',
        label: `难度: ${difficulty.label}`
      })
    }
  }
  
  if (filters.priceType !== 'all') {
    result.push({
      key: 'priceType',
      label: `价格: ${filters.priceType === 'free' ? '免费' : '付费'}`
    })
  }
  
  if (filters.duration) {
    const durationMap = {
      short: '1小时以内',
      medium: '1-5小时',
      long: '5小时以上'
    }
    result.push({
      key: 'duration',
      label: `时长: ${durationMap[filters.duration]}`
    })
  }
  
  return result
})

// 方法
const fetchCourses = async () => {
  try {
    loading.value = true
    
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      keyword: searchKeyword.value.trim(),
      category: activeCategory.value !== 'all' ? activeCategory.value : '',
      difficulty: filters.difficulty,
      priceType: filters.priceType !== 'all' ? filters.priceType : '',
      duration: filters.duration,
      sortBy: sortBy.value
    }
    
    await courseStore.fetchCourseList(params)
    
    courses.value = courseStore.courseList
    total.value = courseStore.total
  } catch (error) {
    ElMessage.error('获取课程列表失败')
    console.error('获取课程列表失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchRecommendedCourses = async () => {
  try {
    // 获取推荐课程
    await courseStore.fetchRecommendedCourses()
    recommendedCourses.value = courseStore.recommendedCourses.slice(0, 4)
  } catch (error) {
    console.error('获取推荐课程失败:', error)
  }
}

const handleSearch = (searchData) => {
  searchKeyword.value = searchData.keyword
  currentPage.value = 1
  fetchCourses()
}

const handleAdvancedSearch = (searchData) => {
  searchKeyword.value = searchData.keyword
  
  // 应用高级筛选条件
  if (searchData.filters.category) {
    activeCategory.value = searchData.filters.category
  }
  if (searchData.filters.difficulty) {
    filters.difficulty = searchData.filters.difficulty
  }
  if (searchData.filters.priceType) {
    filters.priceType = searchData.filters.priceType
  }
  if (searchData.filters.sortBy) {
    sortBy.value = searchData.filters.sortBy
  }
  
  currentPage.value = 1
  fetchCourses()
}

const handleCategoryChange = (category) => {
  activeCategory.value = category
  currentPage.value = 1
  fetchCourses()
}

const handleFilterChange = () => {
  currentPage.value = 1
  fetchCourses()
}

const handleSortChange = () => {
  currentPage.value = 1
  fetchCourses()
}

const handlePageChange = (page) => {
  currentPage.value = page
  fetchCourses()
  
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const handlePageSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchCourses()
}

const clearFilters = () => {
  searchKeyword.value = ''
  activeCategory.value = 'all'
  Object.assign(filters, {
    difficulty: '',
    priceType: 'all',
    duration: '',
    rating: '',
    instructor: ''
  })
  sortBy.value = 'default'
  currentPage.value = 1
  fetchCourses()
}

const removeFilter = (filterKey) => {
  switch (filterKey) {
    case 'keyword':
      searchKeyword.value = ''
      break
    case 'category':
      activeCategory.value = 'all'
      break
    case 'difficulty':
      filters.difficulty = ''
      break
    case 'priceType':
      filters.priceType = 'all'
      break
    case 'duration':
      filters.duration = ''
      break
  }
  
  currentPage.value = 1
  fetchCourses()
}

const viewCourse = (courseId) => {
  router.push(`/courses/${courseId}`)
}

const handleFavorite = async (courseId, isFavorite) => {
  try {
    if (isFavorite) {
      await courseStore.favoriteCourse(courseId)
      ElMessage.success('已添加到收藏')
    } else {
      await courseStore.unfavoriteCourse(courseId)
      ElMessage.success('已取消收藏')
    }
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

const handleEnroll = async (courseId) => {
  try {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }
    
    await courseStore.enrollCourse(courseId)
    ElMessage.success('报名成功')
    
    // 刷新课程列表
    fetchCourses()
  } catch (error) {
    ElMessage.error(error.message || '报名失败')
  }
}

// 监听路由变化
watch(
  () => route.query,
  (newQuery) => {
    if (newQuery.q) {
      searchKeyword.value = newQuery.q
    }
    if (newQuery.category) {
      activeCategory.value = newQuery.category
    }
    if (newQuery.difficulty) {
      filters.difficulty = newQuery.difficulty
    }
    if (newQuery.sort) {
      sortBy.value = newQuery.sort
    }
    
    fetchCourses()
  },
  { immediate: true }
)

// 生命周期
onMounted(async () => {
  await Promise.all([
    fetchCourses(),
    fetchRecommendedCourses()
  ])
})
</script>

<style lang="scss" scoped>
.courses-page {
  min-height: 100vh;
  background: var(--el-bg-color-page);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

// 页面头部
.page-header {
  background: var(--el-bg-color);
  padding: 20px 0 30px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  
  .header-content {
    margin-top: 16px;
    
    .page-title {
      font-size: 2rem;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 8px;
    }
    
    .page-subtitle {
      color: var(--el-text-color-regular);
      font-size: 1.1rem;
    }
  }
}

// 搜索筛选区域
.search-filter-section {
  background: var(--el-bg-color);
  padding: 24px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
  
  .search-bar {
    margin-bottom: 24px;
  }
  
  .filter-tabs {
    margin-bottom: 20px;
    
    :deep(.el-tabs__header) {
      margin-bottom: 0;
    }
    
    :deep(.el-tabs__nav-wrap::after) {
      display: none;
    }
  }
  
  .filter-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    
    .filter-left {
      display: flex;
      align-items: center;
      gap: 12px;
      flex: 1;
      
      .el-select {
        width: 140px;
      }
    }
    
    .filter-right {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .el-select {
        width: 140px;
      }
      
      .view-mode {
        .el-button {
          padding: 8px 12px;
        }
      }
    }
  }
}

// 课程内容区域
.courses-content {
  padding: 24px 0;
  
  .results-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px 0;
    border-bottom: 1px solid var(--el-border-color-lighter);
    
    .results-count {
      color: var(--el-text-color-regular);
      font-size: 14px;
    }
    
    .active-filters {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .filter-label {
        color: var(--el-text-color-secondary);
        font-size: 14px;
      }
      
      .el-tag {
        margin-left: 4px;
      }
    }
  }
  
  .courses-container {
    min-height: 400px;
    
    &.grid-view {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 24px;
    }
    
    &.list-view {
      display: flex;
      flex-direction: column;
      gap: 16px;
    }
  }
  
  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 40px;
    padding-top: 24px;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}

// 推荐课程区域
.recommended-section {
  background: var(--el-bg-color);
  padding: 60px 0;
  border-top: 1px solid var(--el-border-color-lighter);
  
  .section-header {
    text-align: center;
    margin-bottom: 40px;
    
    .section-title {
      font-size: 1.8rem;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 8px;
    }
    
    .section-subtitle {
      color: var(--el-text-color-regular);
      font-size: 1rem;
    }
  }
  
  .recommended-courses {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 24px;
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .filter-controls {
    flex-direction: column;
    align-items: stretch !important;
    gap: 16px !important;
    
    .filter-left,
    .filter-right {
      justify-content: flex-start;
    }
    
    .filter-right {
      justify-content: space-between;
    }
  }
  
  .results-info {
    flex-direction: column !important;
    align-items: flex-start !important;
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 16px;
  }
  
  .page-header {
    .header-content {
      .page-title {
        font-size: 1.5rem;
      }
      
      .page-subtitle {
        font-size: 1rem;
      }
    }
  }
  
  .filter-controls {
    .filter-left {
      flex-wrap: wrap;
      
      .el-select {
        width: 120px;
      }
    }
  }
  
  .courses-container {
    &.grid-view {
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 16px;
    }
  }
  
  .recommended-courses {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)) !important;
    gap: 16px !important;
  }
}

@media (max-width: 480px) {
  .search-filter-section {
    padding: 16px 0;
  }
  
  .filter-controls {
    .filter-left {
      .el-select {
        width: 100px;
        font-size: 12px;
      }
    }
    
    .filter-right {
      .el-select {
        width: 100px;
        font-size: 12px;
      }
    }
  }
  
  .courses-container {
    &.grid-view {
      grid-template-columns: 1fr;
    }
  }
  
  .recommended-courses {
    grid-template-columns: 1fr !important;
  }
  
  .pagination-container {
    :deep(.el-pagination) {
      .el-pagination__sizes,
      .el-pagination__jump {
        display: none;
      }
    }
  }
}
</style>